import 'package:flutter/material.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/models/loc_obj.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/dio_utils/qiniu_oss.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/goods_config/add_addr.dart';
import 'package:xws/widgets/goods_config/add_record.dart';
import 'package:xws/widgets/goods_config/des_box.dart';
import 'package:xws/widgets/goods_config/select_imgs_video.dart';
import 'package:xws/widgets/goods_config/select_quality.dart';
import 'package:xws/widgets/goods_config/set_count.dart';
import 'package:xws/widgets/goods_config/set_price.dart';
import 'package:xws/widgets/safe_scaffold.dart';

/// 编辑物品
class EditGoods extends StatefulWidget {
  const EditGoods({Key? key, required this.goods}) : super(key: key);

  final GoodsObj goods;

  @override
  State<EditGoods> createState() => _EditGoodsState();
}

class _EditGoodsState extends State<EditGoods> {
  late GoodsObj _g;

  @override
  void initState() {
    super.initState();
    _g = widget.goods.copy;
  }

  /// 保存
  Future<void> _save(BuildContext context) async {
    final Map<String, dynamic> check = _g.different(widget.goods);

    if (check.length == 1) {
      ct('内容未变化');
      return;
    }

    loading(context);

    bool uploadRes = await _uploadImgs();
    uploadRes = uploadRes && await _uploadRecord();
    uploadRes = uploadRes && await _uploadVideo();

    if (!uploadRes) {
      close(context);
      return;
    }

    final bool r = await editGoods(_g.different(widget.goods));
    close(context);

    if (r) pop(context, value: _g);
  }

  /// 上传图片
  Future<bool> _uploadImgs() async {
    final List<String> r = await QiniuOSS.uploadFiles(
      _g.photoUrlList,
      Dir.goods,
    );

    if (r.length != _g.photoUrlList.length) {
      et('图片上传未成功');
      return false;
    }

    _g.photoUrlList = r;

    return true;
  }

  /// 上传录音
  Future<bool> _uploadRecord() async {
    if (_g.recordUrl.isEmpty || _g.recordUrl.startsWith('http')) return true;

    final List<String> r = await QiniuOSS.uploadFiles(
      <String>[_g.recordUrl],
      Dir.goods,
    );

    if (r.isEmpty) {
      et('录音上传未成功');
      return false;
    }

    _g.recordUrl = r.single;

    return true;
  }

  /// 上传视频
  Future<bool> _uploadVideo() async {
    if (_g.videoUrl.isEmpty || _g.videoUrl.startsWith('http')) return true;

    final List<String> r = await QiniuOSS.uploadFiles(
      <String>[_g.videoUrl],
      Dir.goods,
    );

    if (r.isEmpty) return false;

    _g.videoUrl = r.single;

    return true;
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      tapToCloseKeyboard: true,
      backgroundColor: white(context),
      titleText: '编辑物品',
      actions: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 10),
          child: AppBtn(onTap: () => _save(context), text: '保存'),
        ),
      ],
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            DesBox(
              initialValue: _g.description,
              onChanged: (String v) => _g.description = v,
            ),
            AddRecord(
              initInd: _g.recordInd,
              initPath: _g.recordUrl,
              onPathChanged: (String? v) => _g.recordUrl = v ?? '',
              onRecoedIndChange: (double? ind) => _g.recordInd = ind ?? 1,
            ),
            _spacer,
            SelectImagesVideo(
              initImages: _g.photoUrlList,
              initVideoPath: _g.videoUrl,
              onImgChanged: (List<String> v) => _g.photoUrlList = v,
              onVideoChanged: (String? v) => _g.videoUrl = v ?? '',
            ),
            _spacer,
            SelectQuality(
              initSelect: _g.age,
              onSelected: (String? v) => _g.age = v ?? '',
            ),
            _spacer,
            AddAddr(
              initValue: _g.city,
              onCoordinateChanged: (LocObj? loc) => _g.setLocation(loc),
            ),
            _spacer,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                SetPrice(
                  init: _g.originalPrice,
                  onChanged: (double? p) => _g.originalPrice = p ?? 0,
                ),
                SetCount(
                  init: _g.count,
                  onChanged: (int v) => _g.count = v,
                ),
              ],
            ),
            const SizedBox(height: 100),
          ],
        ),
      ),
    );
  }

  /// 间隔
  Widget get _spacer => const SizedBox(height: 16);
}
